 <template>
  <div style="padding:20px" class="page-component__scroll el-scrollbar__wrap">
    <el-backtop target=".page-component__scroll .el-scrollbar__wrap"></el-backtop>
    <div class="top_form">
      <el-button @click="save" type="primary">保存</el-button>
      <el-button @click="toCopy()" type="success">复制</el-button>
      <el-button @click="cancel" type="primary" plain>关闭</el-button>
      <el-button  type="success" v-if="form.type != 2" @click="dialogVisible = true">关联客户</el-button>
      <el-button  type="success"  @click="dialogGoods = true">关联商品</el-button>
      <el-button  type="success"  @click="importGoodsStatus = true" >导入商品</el-button>
    </div>
    <el-dialog
      title='导入关联商品'
      :visible.sync="importGoodsStatus"
      width="400px"
    >
      <el-upload
        ref="upload_import"
        action="/api/basCustomer/importBasCustomerGoods"
        :auto-upload="false"
        :before-upload="beforeUpload"
        :headers="upload.headers"
        :limit="1"
        :on-error="handleError"
        :on-success="handleSuccess"
        accept=".xlsx, .xls"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <div class="tpl">
        <el-button
          size="small"
          type="info"
          @click="downloadTemplate('客户关联商品.xlsx')"
        >下载模板
        </el-button>
        <span class="tips">提示：仅允许导入.xls或.xlsx格式文件</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="importStatus=false">取消</el-button>
        <el-button

          type="primary"
          @click="handleSubmit"
        >确认
        </el-button>
      </div>
    </el-dialog>
    <el-form ref="form" :model="form" :inline="true" :rules="rules" size="small" label-width="120px"
             style="margin-top: 20px">
      <el-divider content-position="left">基本信息</el-divider>
      <el-form-item label="编码" prop="code">
        <el-input v-model="form.code" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="客户类型">
        <el-select v-model="form.type" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.t_bas_customer_type"
              :key="index"
              :label="item.label"
              :value="parseInt(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户分类" prop="customerTypeId">
        <treeselect
            v-model="form.customerTypeId"
            :options="typeList"
            placeholder="选择客户分类"
            style="width: 370px"
            :normalizer="normalizer"
        />
      </el-form-item>

      <el-form-item label="客户区域" prop="customerAreaId">
        <treeselect
            v-model="form.customerAreaId"
            :options="areaList"
            placeholder="选择客户区域"
            style="width: 370px"
            :normalizer="normalizer"
        />
      </el-form-item>
      <el-form-item label="来源类型">
        <el-input v-text="form.sourceType == 1?'手工添加':'导入'" leadonly></el-input>
      </el-form-item>
      <div>
        <el-form-item label="是否往来">
          <!--          <el-switch-->
          <!--              v-model="form.isContact"-->
          <!--              active-color="#13ce66"-->
          <!--              :active-value="1"-->
          <!--              :inactive-value="0"-->
          <!--              inactive-color="#ff4949">-->
          <!--          </el-switch>-->
          <el-select v-model="form.isContact" class="edit-input" placeholder="请选择" style="width:  370px;">
            <el-option
                v-for="(item,index) in dict.t_bas_customer_is_contact"
                :key="index"
                :label="item.label"
                :value="parseInt(item.value)"
            />
          </el-select>

        </el-form-item>
        <el-form-item label="是否未级" prop="isLast">
          <el-switch
              v-model="form.isLast"
              active-color="#13ce66"
              :active-value="1"
              :inactive-value="0"
              inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </div>


      <el-form-item label="客户属性" prop="customerAttr">
        <el-select v-model="form.customerAttr" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.t_bas_customer_customer_attr"
              :key="index"
              :label="item.label"
              :value="parseInt(item.value)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="助记符">
        <el-input v-model="form.helpSign" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="拼音">
        <el-input v-model="form.spell" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="简称">
        <el-input v-model="form.shortName" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="连锁名称">
        <el-input v-model="form.chainName" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="form.address" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="店号">
        <el-input v-model="form.shopNo" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="送货地址">
        <el-input v-model="form.deliveryAddress" style="width: 370px;"/>
      </el-form-item>


      <el-form-item label="所属总店">
        <zSelect :value.sync="form.pcustomerId" :showName="form.pcustomerName" url="api/dropDown/basCustomerList" :params="{customerAttr:1}"
                 style="width:  370px;"/>
      </el-form-item>
      <el-form-item label="所属商场">
        <zSelect :value.sync="form.mcustomerId" :showName="form.mcustomerName" url="api/dropDown/basCustomerList"
                 style="width:  370px;"/>
      </el-form-item>
      <el-form-item label="是否直营"  prop="isDirectSale">
        <el-select v-model="form.isDirectSale"
                   clearable
                   style="width:  370px;">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拜访线路">
        <zSelect :value.sync="form.visitLineId" :showName="form.visitLineName" url="api/dropDown/basLineList"
                 style="width:  370px;"/>
      </el-form-item>
      <el-form-item label="拜访时间" prop="visitTime">
        <el-select :value.sync="value" :showName="label" :multiple="multiple"  v-model="form.visitTime"  placeholder="请选择" style="width: 370px;">
            <el-option
              v-for="item in dateScopes"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="拜访频率" prop="visitFrequency">
        <el-input v-model="form.visitFrequency" style="width: 370px;"/>
      </el-form-item>
      <div v-if="form.channel==='1'||form.channel==='2'">
        <el-form-item label="合同区域">
          <zSelect :value.sync="form.dealerAreaIds" :showName="form.dealerAreaName"  multiple url="/api/dropDown/basCustomerAreaList" style="width: 370px;" @change="getdealer"/>

        </el-form-item>
      </div>
      <div v-if="form.channel==='1'">
        <el-form-item label="代理品牌">
          <zSelect :value.sync="form.dealerGoodsBrandIds" :showName="form.dealerGoodsBrandName"  multiple url="api/dropDown/basGoodsBrandList" style="width: 370px;" @change="changeBrand"/>

        </el-form-item>
        <el-form-item label="主销渠道">
          <el-select class="edit-input" placeholder="请选择" style="width:  370px;" @change="selectmain($event)" v-model="form.mainChannelIds">
            <el-option
                v-for="(item,index) in dict.main_channel"
                :key="index"
                :label="item.label"
                :value="(item.value).toString()"
            />
          </el-select>
        </el-form-item>
      </div>
      <div v-if="form.channel==='2'">
        <el-form-item label="合作渠道">
          <el-select class="edit-input" placeholder="请选择" style="width:  370px;" @change="selectco($event)" v-model="form.coChannelIds">
            <el-option
                v-for="(item,index) in dict.co_channel" multiple
                :key="index"
                :label="item.label"
                :value="(item.value).toString()"
            />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="餐饮类型" v-if="form.channel==='6'">
        <el-select v-model="form.cateringType" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.catering_type"
              :key="index"
              :label="item.label"
              :value="(item.value).toString()"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商超类型" v-if="form.channel==='7'">
        <el-select v-model="form.supermarketType" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.supermarket_type"
              :key="index"
              :label="item.label"
              :value="(item.value).toString()"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="终端分类">
        <el-select v-model="form.endCustomerType" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.customer_type"
              :key="index"
              :label="item.label"
              :value="(item.value).toString()"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年度销量">
        <el-select v-model="form.yearlySaleCount" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.yearly_sale_count"
              :key="index"
              :label="item.label"
              :value="(item.value).toString()"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员等级">
        <z-select
          url="/api/dropDown/memberLevelList"
          :popperAppendToBody="false"
          size="999"
          style="width:  370px;"
          :value.sync="form.memberLevelId"
          :showName="form.memberLevelName"
          labelKey="memberName"
          valueKey="id"
          @change="$event=>setQuery('monthlyStock',$event)"
        />
      </el-form-item>
      <!--     <el-form-item label="所属商场编码">-->
      <!--       <el-input v-model="form.mcustomerCode" style="width: 370px;" />-->
      <!--     </el-form-item>-->
      <!--     <el-form-item label="所属商场名称">-->
      <!--       <el-input v-model="form.mcustomerName" style="width: 370px;" />-->
      <!--     </el-form-item>-->

<!--      <el-form-item label="所属商贸公司">-->
<!--        <zSelect :value.sync="fCustomerIds" multiple :showName="form.fcustomerName" url="api/dropDown/basCustomerList" :params="{type:2}"-->
<!--                 style="width:  370px;"/>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="所属二批">-->
<!--        <zSelect :value.sync="sCustomerIds" multiple :showName="form.scustomerName" url="api/dropDown/basCustomerList" :params="{type:3}"-->
<!--                 style="width:  370px;"/>-->
<!--      </el-form-item>-->

      <el-divider content-position="left">联系信息</el-divider>
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="form.contactName" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="联系人电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <treeselect
            v-model="form.deptId"
            :options="depts"
            placeholder="选择部门"
            style="width:  370px"
            :normalizer="normalizer"
        />
      </el-form-item>


      <el-form-item label="业务员" prop="">
        <zSelect :value.sync="form.userId" :showName="form.userName" url="api/dropDown/sysUserList" :params="{businessAttr:'3'}"
                 style="width:  370px;"/>
      </el-form-item>
      <el-form-item label="结算人" prop="">
        <zSelect :value.sync="form.payeeId" :showName="form.payeeName" url="api/dropDown/sysUserList" :params="{businessAttr:'7'}"
                 style="width:  370px;"/>
      </el-form-item>
      <el-form-item label="文员">
        <zSelect :value.sync="form.clerkId" :showName="form.clerkName" url="api/dropDown/sysUserList" :params="{businessAttr:'4'}"
                 style="width:  370px;"/>
      </el-form-item>
      <el-form-item label="结算方式" prop="settlementId">
        <zSelect :value.sync="form.settlementId" :showName="form.settlementName" url="api/dropDown/basSettlementList" style="width:  370px;"/>
      </el-form-item>
      <el-form-item label="结账类别">
        <el-select v-model="form.settlebillType" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.t_bas_customer_settlebill_type"
              :key="index"
              :label="item.label"
              :value="parseInt(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="余额">
        <el-input v-model="form.balance" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="物流系数">
        <el-input v-model="form.logisticCoefficient" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="渠道类型">
        <el-select v-model="form.channel" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.customer_channel"
              :key="index"
              :label="item.label"
              :value="(item.value).toString()"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属仓库" prop="warehouseId">
        <zSelect :value.sync="form.warehouseId" :showName="form.warehouseName" url="api/dropDown/basWarehouseList" style="width:  370px;"/>
      </el-form-item>
      <el-form-item label="所属销售体系" prop="saleSystemId">
        <zSelect :value.sync="form.saleSystemId" :showName="form.saleSystemName" url="api/dropDown/basSaleSystemList" style="width:  370px;"/>
      </el-form-item>

      <el-form-item label="经度">
        <el-input v-model="form.lng" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="纬度">
        <el-input v-model="form.lat" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="坐标（经纬度）">
        <el-input v-model="form.location" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="打印抬头信息">
        <!--        <el-input v-model="form.letterhead" style="width: 370px;"/>-->
        <zSelect style="width: 370px;" jsonAdd  :json.sync="form.letterhead"  url=""></zSelect>
      </el-form-item>
      <el-form-item label="附件url">
        <el-input v-model="form.fileUrl" style="width: 370px;"/>
      </el-form-item>
      <!--     <el-form-item label="上传状态">-->
      <!--       未设置字典，请手动设置 Select-->
      <!--     </el-form-item>-->
      <el-form-item label="排序">
        <el-input-number v-model="form.seq" :min="1" label="排序" style="width: 370px;"></el-input-number>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="form.status" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
              v-for="(item,index) in dict.common_status"
              :key="index"
              :label="item.label"
              :value="parseInt(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" style="width: 370px"/>
      </el-form-item>
      <el-divider content-position="left">银行账号</el-divider>

      <el-form-item label="营业执照编号">
        <el-input v-model="form.businessLicense" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="税号">
        <el-input v-model="form.taxNo" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="开户银行">
        <el-input v-model="form.bankOpenName" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="银行账号">
        <el-input v-model="form.bankAccount" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="开户名">
        <el-input v-model="form.bankAccountName" style="width: 370px;"/>
      </el-form-item>

      <el-divider content-position="left">额度</el-divider>
      <el-form-item label="铺底金额">
        <el-input v-model="form.depositAmount" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="信用额度">
        <el-input v-model="form.creditLimit" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="信用等级">
        <el-select v-model="form.creditLevel" class="edit-input" placeholder="请选择" style="width:  370px;">
          <el-option
            v-for="(item,index) in dict.t_bas_customer_credit_level"
            :key="index"
            :label="item.label"
            :value="parseInt(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="抵扣券">
        <el-input v-model="form.deductionAmount" readonly style="width: 370px;"/>
      </el-form-item>
      <el-divider content-position="left">图片信息</el-divider>
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="公章图片" name="first">
          <el-upload
          ref="upload"
          :limit="1"
          accept=".jpg, .png"
          :action="upload.url"
          :headers="upload.headers"
          :file-list="upload.fileList"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading" @click="submitUpload">上传到服务器</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
          <el-carousel :interval="4000" type="card" height="600px">
            <el-carousel-item v-for="(item,index) in upload.stampImgList" :key="item">
              <div class="demo-image__preview">
                <el-image
                  width="800px"
                  heigth="600px"
                  fit="fill"
                  :src="item.path"
                >
                </el-image>
                <i class="el-icon-close jIcon" @click="delStampImgImage(index)"></i>
              </div>
            </el-carousel-item>
          </el-carousel>
        </el-tab-pane>
        <el-tab-pane label="门店图片" name="second">
          <el-upload
            ref="upload1"
            :limit="1"
            accept=".jpg, .png"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList1"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess1"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading" @click="submitUpload1">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <el-carousel :interval="4000" type="card" height="600px">
            <el-carousel-item v-for="item in upload.imageList" :key="item">
              <div class="demo-image__preview">
                <el-image
                  width="800px"
                  heigth="600px"
                  fit="fill"
                  :src="item.path"
                >
                </el-image>
              </div>
            </el-carousel-item>
          </el-carousel>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-dialog
      title="关联客户"
      :visible.sync="dialogVisible"
      width="60%"
      height="450"
      max-height="450"
      >
      <div class="jRow">
        <el-button @click="changeTagType(2)" v-if="form.type != 1">关联商贸公司</el-button>
        <el-button @click="changeTagType(3)" v-if="form.type == 1">关联二批代理</el-button>
      </div>
      <el-tabs v-model="activeName" type="card" >
        <el-tab-pane label="商贸公司" name="first">
          <el-table
            :data="form.fcustomerList"
            style="width: 100%"
            max-height="250"
          >
            <el-table-column   prop="fcustomerName" label="名称" fixed="left"/>
            <el-table-column   prop="fcustomerCode" label="编码"/>
            <el-table-column   prop="type" label="客户类型">
              <template slot-scope="scope">
                商贸公司
              </template>
            </el-table-column>
            <el-table-column  label="操作">
              <template slot-scope="scope">
                <el-button @click="delFcustomer(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="二批代理" name="second" v-if="form.type == 1"><el-table
          :data="form.scustomerList"
          style="width: 100%"
          max-height="250"
        >
          <el-table-column   prop="scustomerName" label="名称" fixed="left"/>
          <el-table-column   prop="scustomerCode" label="编码"/>
          <el-table-column   prop="type" label="客户类型">
            <template slot-scope="scope">
              二级代理
            </template>
          </el-table-column>
          <el-table-column  label="操作">
            <template slot-scope="scope">
              <el-button @click="delScustomer(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table></el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="savesCustomer">确 定</el-button>
     </span>
    </el-dialog>
    <el-dialog
      title="选择客户"
      :visible.sync="relationCompany"
      width="50%"
    >
      <jCustomer v-if="relationCompany" @selectCustomerList="changeCustmoer" :ids="form.fcustomerIds" :ctype="tagType"></jCustomer>
    </el-dialog>
    <el-dialog
      title="关联商品"
      :visible.sync="dialogGoods">
      <j-goods :dialogGoods="dialogGoods" @addGoods="updateGoods" :customerType="form.type" :customerId="id" :type="1" :scope="0"></j-goods>
    </el-dialog>
  </div>
</template>

<script>
import crudBasCustomer from '@/api/erp/basCustomer'
import Treeselect from '@riophae/vue-treeselect'
import {getAreaTree} from "@/api/erp/basCustomerArea";
import {getDepts} from "@/api/system/dept";
import {getCustomerTypeTree} from "@/api/erp/basCustomerType";
import pagination from '@crud/Pagination'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import jCustomer from "@/components/jCustomer/jCustomer";
import { getToken } from "@/utils/auth";
import jGoods from "@/components/jGoods/jGoods";
import request from "@/utils/request";
import {addOrSaveBasCustomerGoods, addOrSaveBasCustomerRelation} from "@/api/erp/basCustomer";


const defaultForm = {
  id: null,
  code: null,
  name: null,
  type: null,
  sourceType: null,
  isContact: null,
  isLast: null,
  customerAttr: null,
  channelType: null,
  helpSign: null,
  spell: null,
  shortName: null,
  chainName: null,
  address: null,
  shopNo: null,
  taxNo: null,
  businessLicense: null,
  depositAmount: null,
  pcustomerId: null,
  pcustomerCode: null,
  pcustomerName: null,
  mcustomerId: null,
  mcustomerCode: null,
  mcustomerName: null,
  warehouseId: null,
  warehouseCode: null,
  warehouseName: null,
  saleSystemId: null,
  saleSystemCode: null,
  saleSystemName: null,
  fcustomerId: null,
  fcustomerCode: null,
  fcustomerName: null,
  scustomerId: null,
  scustomerCode: null,
  scustomerName: null,
  bankId: null,
  bankAccount: null,
  bankOpenName: null,
  contactName: null,
  contactPhone: null,
  customerAreaId: null,
  customerAreaCode: null,
  customerAreaName: null,
  customerTypeId: null,
  customerTypeCode: null,
  customerTypeName: null,
  visitLineId: null,
  visitLinedCode: null,
  visitLineName: null,
  visitTime:'',
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  payeeId: null,
  payeeCode: null,
  payeeName: null,
  clerkId: null,
  clerkCode: null,
  clerkName: null,
  settlementId: null,
  settlementCode: null,
  settlementName: null,
  settlebillType: null,
  balance: null,
  creditLimit: null,
  creditLevel: null,
  lng: null,
  lat: null,
  location: null,
  letterhead: "[{id:' ',name:' '}]",
  imageUrl: null,
  stampImageUrl: null,
  fileUrl: null,
  uploadStatus: null,
  seq: null,
  status: 1,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  fcustomerList: null,
  scustomerList: null,
  fcustomerIds: null,
  isDirectSale: 0,
  deductionAmount:null,
  memberLevelName:null,
  memberLevelId:null
}
export default {
  name: 'BasCustomer',
  components: {Treeselect,crudBasCustomer,pagination,rrOperation,jCustomer,jGoods},
  dicts: ['t_bas_customer_credit_level', 'common_status',
    'customer_channel','main_channel', 'co_channel','catering_type','supermarket_type','yearly_sale_count','customer_type','t_bas_customer_is_contact', 't_bas_customer_customer_attr', 't_bas_customer_source_type', 't_bas_customer_settlebill_type','t_bas_customer_type'],
  provide(){
    return {

      type: this.ctype
    }
  },
  watch: {
    "form.stampImageUrl"(){
      this.upload.stampImgList = JSON.parse(this.form.stampImageUrl)
    },
    "form.imageUrl"(){
      this.upload.imageList = JSON.parse(this.form.imageUrl)
    },
  },
  mounted() {
  },
  data() {
    return {
      multiple:true,
      dateScopes: [{//周选择
          label: '周一', value: 1
        }, {
          label: '周二', value: 2
        }, {
          label: '周三', value: 3
        }, {
          label: '周四', value: 4
        }, {
          label: '周五', value: 5
        }, {
          label: '周六', value: 6
        }, {
          label: '周日', value: 7
        }],
        mainChannel:[
          {name: '餐饮', value: 1},
          {name: '流通', value: 2},
          {name: '商超', value: 3},
          {name: '全渠道', value: 4},
        ],
        coChannel:[
          {name: '餐饮', value: 1},
          {name: '流通', value: 2},
          {name: '商超', value: 3},
          {name: '全渠道', value: 4},
        ],
      permission: {
        add: ['admin', 'basCustomer:add'],
        edit: ['admin', 'basCustomer:edit'],
        del: ['admin', 'basCustomer:del'],
        import: ['admin', 'basCustomer:import'],
        export: ['admin', 'basCustomer:export'],
        copy: ['admin', 'basCustomer:copy'],
        upload: ['admin', 'basCustomer:upload'],
        download: ['admin', 'basCustomer:download'],
        enable: ['admin', 'basCustomer:enable'],
        disable: ['admin', 'basCustomer:disable'],
      },
      options: [{
        value: 1 ,
        label: '是'
      }, {
        value: 0 ,
        label: '否'
      }],
      fCustomerIds:[],
      sCustomerIds:[],
      rules: {
        saleSystemId: [
          {required: true, message: '销售不能为空', trigger: 'blur'}
        ],
        contactName: [
          {required: true, message: '联系人不能为空', trigger: 'blur'}
        ],
        contactPhone: [
          {required: true, message: '联系电话不能为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        isLast: [
          {required: true, message: '是否未级不能为空', trigger: 'blur'}
        ],
        customerAttr: [
          {required: true, message: '客户属性不能为空', trigger: 'blur'}
        ],
        customerAreaId: [
          {required: true, message: '客户区域不能为空', trigger: 'blur'}
        ],
        customerTypeId: [
          {required: true, message: '客户分类不能为空', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '部门不能为空', trigger: 'blur'}
        ],
        userId: [
          {required: true, message: '业务员不能为空', trigger: 'blur'}
        ],
        payeeId: [
          {required: true, message: '结算人不能为空', trigger: 'blur'}
        ],
        settlementId: [
          {required: true, message: '结算方式不能为空', trigger: 'blur'}
        ],
        warehouseId:[
          {required: true, message: '所属仓库不能为空', trigger: 'blur'}
        ],
      },
      typeList: [],
      areaList: [],
      depts: [],
      form: defaultForm,
      id: 0,
      dialogVisible: false,
      relationCompany: false,
      companyTable:[],
      agentTable:[],
      activeName: 'first',
      ctype: 2,
      tagType: 0,
      dialogGoods:false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url:'',
        // 上传的文件列表
        fileList: [],
        fileList1: [],
        // 公章图片列表
        stampImgList:[],
        // 门店图片列表
        imageList: []
      },
      importGoodsStatus:false
    }
  },
  created() {
    this.upload.url = window.location.href.split('/').slice(0,3).join('/')+'/api/common/uploadImage'
    let id = this.$route.query.id
    if (id == 0){
      this.form= {
        id: null,
        code: null,
        name: null,
        type: null,
        sourceType: null,
        isContact: null,
        isLast: null,
        customerAttr: null,
        channelType: null,
        helpSign: null,
        spell: null,
        shortName: null,
        chainName: null,
        address: null,
        shopNo: null,
        taxNo: null,
        businessLicense: null,
        depositAmount: null,
        pcustomerId: null,
        pcustomerCode: null,
        pcustomerName: null,
        mcustomerId: null,
        mcustomerCode: null,
        mcustomerName: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        saleSystemId: null,
        saleSystemCode: null,
        saleSystemName: null,
        fcustomerId: null,
        fcustomerCode: null,
        fcustomerName: null,
        scustomerId: null,
        scustomerCode: null,
        scustomerName: null,
        bankId: null,
        bankAccount: null,
        bankOpenName: null,
        contactName: null,
        contactPhone: null,
        customerAreaId: null,
        customerAreaCode: null,
        customerAreaName: null,
        customerTypeId: null,
        customerTypeCode: null,
        customerTypeName: null,
        deptId: null,
        deptCode: null,
        deptName: null,
        userId: null,
        userCode: null,
        userName: null,
        payeeId: null,
        payeeCode: null,
        payeeName: null,
        clerkId: null,
        clerkCode: null,
        clerkName: null,
        settlementId: null,
        settlementCode: null,
        settlementName: null,
        settlebillType: null,
        balance: null,
        creditLimit: null,
        creditLevel: null,
        lng: null,
        lat: null,
        location: null,
        letterhead: '[{"id":" ","name":" "}]',
        imageUrl: null,
        stampImageUrl: null,
        fileUrl: null,
        uploadStatus: null,
        seq: null,
        status: 1,
        remark: null,
        createUserId: null,
        createUserCode: null,
        createUserName: null,
        createTime: null,
        updateUserId: null,
        updateUserCode: null,
        updateUserName: null,
        updateTime: null,
        fcustomerList: null,
        scustomerList: null,
        isDirectSale: 0,
        dealerAreaList:[],
        dealerAreaName:'',
        dealerAreaIds:'',
        dealerGoodsBrandIds:'',
        dealerGoodsBrandName:'',
        dealerGoodsBrandList:[],
        mainChannelIds:'',
        mainChannelName:'',
        mainChannelList:[],
        coChannelIds:'',
        coChannelName:'',
        coChannelList:[],
        contributorGoodsIds:'',
        contributorGoodsName:'',
      };
      this.getTypeList()
      this.getAreaList()
      this.getDepts()
      return
    }
    if (id != null) {
      //查询商品详情
      this.id = id

      //从cookie中获取数据
      // let _form = Cookies.get("customerForm_" + id)
      // if (_form) {
      //   this.form = JSON.parse(_form)
      // } else {
      //   //如果没有数据，就进行联网查询
      //   if (id != 0) {
      //     this.getOneById(id)
      //   }
      // }
      // try {
      //
      //   let _form = JSON.parse(localStorage.getItem("customerForm_" + id));
      //   if (_form) {
      //     this.form = _form
      //   } else {
      //     if (id != 0) {
      //       this.getOneById(id)
      //     }
      //   }
      // } catch (e) {
      // //   //如果没有数据，就进行联网查询
      //   if (id != 0) {
          this.getOneById(id)
        // }
      // }
    } else {
      this.getCopyId(window.location.href.match(/copyId=\d+$/)[0].split('=')[1])
    }
    this.getTypeList()
    this.getAreaList()
    this.getDepts()
    this.upload.stampImgList = JSON.parse(this.form.stampImageUrl)
    this.upload.imageList = JSON.parse(this.form.imageUrl)
  },

  destroyed() {
    // Cookies.set("customerForm_" + this.id, JSON.stringify(this.form))
    if (!this.saveFlag) {
      localStorage.setItem("customerForm_" + this.id, JSON.stringify(this.form));
    }
  },
  methods: {
    getdealer(){
      this.form.dealerAreaList=[]
      this.form.dealerAreaIds.split(',').map(item=>{
        this.form.dealerAreaList.push({customerAreaId:item})
      })
    },
    changeBrand(){
      this.form.dealerGoodsBrandList=[]
      this.form.dealerGoodsBrandIds.split(',').map(item=>{
        this.form.dealerGoodsBrandList.push({goodsBrandId:item})
      })
    },
    selectco(e){
      this.form.coChannelList=this.coChannel.filter(item=>{
        if (item.value==e) {
          return item
        }
      })
      this.$forceUpdate()
    },
    selectmain(e){
      this.form.mainChannelList=this.mainChannel.filter(item=>{
        if (item.value==e) {
          return item
        }
      })
      this.$forceUpdate()
    },
    delStampImgImage(index) {
      this.$confirm('此操作将删除该图片, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.upload.stampImgList.splice(index, 1)
        this.form.stampImgUrl = JSON.stringify(this.upload.stampImgList)
        console.log(this.form.stampImgUrl)
      }).catch(() => {
      })
    },
    savesCustomer(){
      const visitTime = typeof this.form.visitTime === 'object' && JSON.stringify(this.form.visitTime)
      const form = Object.assign({},this.form,{visitTime})
      addOrSaveBasCustomerRelation(form).then(res=>{
        this.$message.success(res.msg)
      })
      this.dialogVisible = false
      setTimeout(()=>{this.getOneById(this.$route.query.id)},1000)
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt2M
    },
    handleError(err, file, fileList) {
      this.crud.notify(
        ' -_- !~~ 服务器开小差了，稍后重试',
        CRUD.NOTIFICATION_TYPE.WARNING
      )
    },
    handleSuccess(response, file, fileList) {
      if (response !== '导入成功') {
        const a = document.createElement('a')
        a.setAttribute('href', response.data.result)
        a.click()
      } else {
        this.crud.notify(response, CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.$refs.upload.clearFiles()
        this.uploadDialgShow = false
        this.crud.refresh()
      }
    },

    delImage(index) {
      this.$confirm('此操作将永久删除该图片, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.upload.imageList.splice(index, 1)
        this.form.imageUrl = JSON.stringify(this.upload.imageList)
      }).catch(() => {
      })
    },
    downloadTemplate(name) {
      request({
        url: 'api/common/downloadExcelTemplate?name=' + name,
        method: 'get',
        responseType: 'blob'
      }).then((res) => {
        const a = document.createElement('a')
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel'
        })
        const objectUrl = URL.createObjectURL(blob)
        a.setAttribute('href', objectUrl)
        a.setAttribute('download', name)
        a.click()
      })
    },
    handleAdd() {
      this.upload.fileList1 = [];
      this.upload.fileList = [];
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    submitUpload1() {
      this.$refs.upload1.submit();
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    //公章
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      if(this.upload.stampImgList === null) {
        this.upload.stampImgList = []
      }
      this.upload.stampImgList.push({ path:response.data.path,realName:response.data.realName,id:response.data.id })
      this.form.stampImageUrl = JSON.stringify(this.upload.stampImgList)
      this.save()
    },
    //门店
    handleFileSuccess1(response, file, fileList) {
      this.upload.isUploading = false;
      if(this.upload.imageList === null) {
        this.upload.imageList = []
      }
      this.upload.imageList.push({ path:response.data.path,realName:response.data.realName,id:response.data.id })
      this.form.imageUrl = JSON.stringify(this.upload.imageList)
      this.save()
    },
    delFcustomer(index){
      this.form.fcustomerList.splice(index,1)
    },
    delScustomer(index){
      this.form.scustomerList.splice(index,1)
    },
    changeTagType(type){
      this.tagType = type
      this.relationCompany = true
    },
    changeCustmoer(val){

      if (this.tagType === 2){
        val.forEach(item=>{
          if (this.form.fcustomerList == null ){this.form.fcustomerList = []}
          if(this.form.fcustomerList.find(v=>item.id === v.id) == undefined){
            let item1 = {}
            item1.customerId = this.customerId
            item1.fcustomerId = item.id
            item1.fcustomerCode = item.code
            item1.fcustomerName = item.name
            this.form.fcustomerList.push(item1)
          }else {
            alert(`${item.name}已存在选择列表中`)
          }
          this.relationCompany = false
        })
      }else {
        console.log(this.form.scustomerList)
        val.forEach(item => {
          if (this.form.scustomerList == null) {
            this.form.scustomerList = []
          }
          if (this.form.scustomerList.find(v => item.id === v.id) == undefined) {
            let item1 = {}
            item1.customerId = this.customerId
            item1.scustomerId = item.id
            item1.scustomerCode = item.code
            item1.scustomerName = item.name
            this.form.scustomerList.push(item1)
          } else {
            alert(`${item.name}已存在选择列表中`)
          }
          this.relationCompany = false
        })
      }
      },
    handleSubmit() {
      // this.crud.doImport()
      this.$refs.upload_import.submit()
    },
    getOneById(id) {
      const that = this
      crudBasCustomer.get({id: id}).then(res => {

        that.form = res.data.content[0]
        if(!that.form.letterhead){
          that.form.letterhead = '[{"id":" ","name":" "}]'
        }
        this.form.visitTime=JSON.parse(this.form.visitTime)||''
        that.form.isDirectSale = that.form.isDirectSale || 0
        if (that.form.dealerAreaList) {
          that.form.dealerAreaIds=that.form.dealerAreaList.map(item=>{
          return item.customerAreaId
          }).join(',')
        }
        if (that.form.mainChannelList) {
          that.form.mainChannelIds=that.form.mainChannelList[0].value
        }
        if (that.form.coChannelList) {
          that.form.coChannelIds=that.form.coChannelList[0].value
        }

        that.form.dealerGoodsBrandIds=that.form.dealerGoodsBrandList.map(item=>{
          return item.goodsBrandId
        }).join(',')
        this.$forceUpdate()
        if(!this.form.letterhead){
          this.form.letterhead = '[{"id":" ","name":" "}]'
        }
      })
    },
    getCopyId(id) {
      const that = this
      crudBasCustomer.copy(id).then(res => {
        that.form = res.data
        if(!that.form.letterhead){
          that.form.letterhead = '[{"id":" ","name":" "}]'
        }
        that.form.channel=(that.form.channel).toString()
      })
    },
    getAreaList() {
      getAreaTree().then(res => {
        this.areaList = res
      })
    },
    // 获取弹窗内部门数据
    getDepts() {
      getDepts({status: 1}).then(res => {
        this.depts = res
      })
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.pcustomerId =  this.form.pcustomerId || 0
          this.form.pCustomerId = this.form.pcustomerId
          this.form.mcustomerId =  this.form.mcustomerId || 0
          this.form.mCustomerId = this.form.mcustomerId
          console.log(this.form.visitTime)
          const visitTime = this.form.visitTime && typeof this.form.visitTime === 'object' ? JSON.stringify(this.form.visitTime):this.form.visitTime
          this.form.visitLineId = this.form.visitLineId || 0
          const form = Object.assign({},this.form,{visitTime})
          crudBasCustomer.add(form).then(res => {
            if (res.status == 200) {
              this.$message.success(res.msg)
              // this.$store.dispatch("tagsView/delView", this.$route);
              this.$router.push({
                  path: '/bas/customer/basCustomerDetail/' + res.data.id,
                  query: {id: res.data.id},
                  meta: {title: '商品档案详情'}
                }
              )
              // this.cancel()
              //删除cookie
              // Cookies.remove("customerForm_" + this.id)

              // localStorage.removeItem("customerForm_" + this.id);
              // this.form = JSON.parse(JSON.stringify(defaultForm))
              // this.cancel()
            } else {
              // this.$message.error((res.))
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    cancel() {
      this.$store.dispatch('tagsView/delView', {
        path: '/bas/customer/basCustomerDetail/' + this.id,
      }).then(({visitedViews}) => {
        this.saveFlag = true
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView)
        } else {
          // now the default is to redirect to the home page if there is no tags-view,
          // you can adjust it according to your needs.
          // if (view.name === 'Dashboard') {
          //   // to reload home page
          //   this.$router.replace({path: '/redirect' + view.fullPath})
          // } else {
          //   this.$router.push('/')
          // }
        }
      }).catch(res => {
        console.log(res);
      })
    },
    updateGoods(val){
      addOrSaveBasCustomerGoods({list:val}).then(res=>{
        this.$alert(res.msg, '提示')
        this.dialogGoods = false
      })
      this.crud.resetQuery()
    },
    toCopy() {

      // let _data = JSON.parse(JSON.stringify(this.form))
      // _data.id=null
      // _data.code = this.form.code + "1"
      // localStorage.setItem("customerForm_" + _data.code, JSON.stringify(_data));
      //打开一个新增界面
      this.$router.push({
        path: `/bas/customer/basCustomerDetail/copyId=${this.$route.query.id}`,
        title: '复制用户档案'
      })

    },
    paste() {

    },
    getTypeList() {
      getCustomerTypeTree({page: 0, size: 999}).then(res => {
        this.typeList = res
      })
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.beforeToCU](crud, form) {
      console.log(this.form,'新增与编辑前做的操作');
    }

  }
}
</script>

<style scoped>
.jRow{
  margin-bottom: 10px;
}
.jText{
  line-height: 30px;
}
</style>
